from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from langgraph.checkpoint.postgres import PostgresSaver
import os

DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://root:15671040800q@49.233.41.129:5433/chatbot")

engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

def create_saver(self):
    """
    创建一个PostgresSaver实例，用于保存和恢复状态。
    """
    return PostgresSaver.from_conn_string(self.__db_url)